package com.modernyuanshiren;

import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class PermCombinationSupplier implements Supplier<String> {
	private Function<Integer, String> mapper = String::valueOf;

	private CombinationSupplier comSupplier;
	private PermSupplier<String> permSupplier;

	/**
	 * if pick 4 digits out of 0~9,then numOfDefineDigits is 10(as 0~9 are 10
	 * digits),and numOfResultDigits is 4.
	 * 
	 * @param numOfDefineDigits
	 * @param numOfResultDigits
	 */
	public PermCombinationSupplier(int numOfDefineDigits, int numOfResultDigits) {
		comSupplier = new CombinationSupplier(numOfDefineDigits,
				numOfResultDigits);
	}

	/**
	 * default display : 0からの数字。
	 * 
	 * @param mapper
	 *            0からの数字->表示用文字列
	 */
	public void setDisplayMapper(Function<Integer, String> mapper) {
		this.mapper = mapper;
	}

	@Override
	public String get() {
		while (true) {
			if (permSupplier == null) {
				try {
					List<String> init = Arrays.asList(comSupplier.get().split(""));
					permSupplier = new PermSupplier<>(init);
				} catch (Exception e) {
					throw new RuntimeException("完了");
				}
			} else {
				try {
					return getResult();
				} catch (Exception e) {
					permSupplier = null;
				}
			}
		}
	}

	private String getResult() {
		return permSupplier.get().stream().map(Integer::valueOf).map(mapper)
				.collect(Collectors.joining());
	}
}